<template>
  <div>
    <h1>订单管理</h1>
    <el-card>
      <div class="search-bar">
        <el-select v-model="searchStatus" placeholder="订单状态" clearable style="width: 120px;" size="small">
          <el-option v-for="(label, value) in statusMap" :key="value" :label="label" :value="value" />
        </el-select>
        <el-date-picker v-model="searchOrderTime" type="datetime" placeholder="下单时间" style="width: 160px;" clearable size="small" />
        <el-input v-model="searchTableId" placeholder="桌号" style="width: 80px;" clearable size="small" />
        <el-input v-model="searchAmount" placeholder="金额" style="width: 80px;" clearable size="small" />
        <el-select v-model="searchPayStatus" placeholder="支付状态" clearable style="width: 100px;" size="small">
          <el-option label="未支付" :value="1" />
          <el-option label="已支付" :value="2" />
        </el-select>
        <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
        <el-button @click="resetSearch" size="small">重置</el-button>
      </div>
      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="payStatus" label="支付状态" width="120" />
        <el-table-column prop="tableId" label="桌号" width="100" />
        <el-table-column prop="amount" label="金额" width="120" />
        <el-table-column prop="createdAt" label="下单时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
            <el-button size="small" type="warning" @click="updateOrderStatus(scope.row)">修改状态</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="700px" @close="resetDetailDialog">
      <el-table :data="orderDetailList" style="width: 100%">
        <el-table-column prop="id" label="明细ID" width="80" />
        <el-table-column prop="dishId" label="菜品ID" width="100" />
        <el-table-column prop="dishName" label="菜品名称" width="120" />
        <el-table-column prop="dishPrice" label="单价" width="100" />
       
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <img v-if="scope.row.dishImage" :src="getImagePreview(scope.row.dishImage)" alt="图片"
              style="width: 60px; height: 60px; object-fit: cover; border-radius: 6px;" />
          </template>
        </el-table-column>
        <el-table-column prop="tableId" label="桌号" width="80" />
        <el-table-column prop="count" label="数量" width="80" />
        <el-table-column prop="amount" label="金额" width="100" />
        <el-table-column prop="orderTime" label="下单时间" width="180" />
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="detailTotal"
          :page-size="detailPageSize"
          :page-sizes="[5, 10, 20]"
          v-model:current-page="detailPageNum"
          v-model:page-size="detailPageSize"
          @current-change="handleDetailPageChange"
          @size-change="handleDetailSizeChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import axios from '../utils/request'
import baseURL from '../config/baseURL'

const search = ref('')
const orders = ref([])
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)
const detailDialogVisible = ref(false)
const orderDetailList = ref([])
const detailTotal = ref(0)
const detailPageNum = ref(1)
const detailPageSize = ref(5)
const statusMap = {
  1: '等待制作中',
  2: '制作中',
  3: '制作完成',
  4: '待上菜',
  5: '已上菜',
  6: '已完成'
}
let currentOrderId = null
const searchStatus = ref()
const searchOrderTime = ref()
const searchTableId = ref()
const searchAmount = ref()
const searchPayStatus = ref()

function fetchOrders() {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }
  if (searchStatus.value) params.status = searchStatus.value
  if (searchOrderTime.value) params.orderTime = typeof searchOrderTime.value === 'string' ? searchOrderTime.value : searchOrderTime.value.toISOString().slice(0, 16)
  if (searchTableId.value) params.tableId = searchTableId.value
  if (searchAmount.value) params.amount = searchAmount.value
  if (searchPayStatus.value) params.payStatus = searchPayStatus.value
  axios.post('/api/order/listOrder', params).then(res => {
    if (res.data.code === 1) {
      const payStatusMap = {
        1: '未支付',
        2: '已支付'
      }
      orders.value = res.data.data.data.map(item => ({
        orderNo: item.id,
        status: statusMap[item.status] || '未知',
        payStatus: payStatusMap[item.payStatus] || '未知',
        tableId: item.tableId,
        amount: item.amount,
        createdAt: item.orderTime.replace('T', ' ').slice(0, 16)
      }))
      total.value = res.data.data.total
    }
  })
}

function handleSearch() {
  currentPage.value = 1
  fetchOrders()
}
function handlePageChange(page) {
  currentPage.value = page
  fetchOrders()
}
function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}
function viewDetail(row) {
  currentOrderId = row.orderNo
  console.log(currentOrderId)
  detailDialogVisible.value = true
  detailPageNum.value = 1
  fetchOrderDetail()
}
function fetchOrderDetail() {
  axios.post('/api/order/list', {
    orderId: currentOrderId,
    pageNum: detailPageNum.value,
    pageSize: detailPageSize.value
  }).then(async res => {
    if (res.data.code === 1) {
      let detailList = res.data.data.data.map(item => ({
        ...item,
        orderTime: item.orderTime.replace('T', ' ').slice(0, 16)
      }))
      // 并发请求所有菜品信息
      const dishPromises = detailList.map(detail =>
        axios.post('/api/dish/list', {
          id: detail.dishId,
          pageNum: 1,
          pageSize: 1
        })
      )
      const dishResults = await Promise.all(dishPromises)
      detailList = detailList.map((detail, idx) => {
        const dishData = dishResults[idx].data.data.data[0] || {}
        return {
          ...detail,
          dishName: dishData.name || '',
          dishPrice: dishData.price || '',
          dishImage: dishData.image || ''
        }
      })
      orderDetailList.value = detailList
      detailTotal.value = res.data.data.total
    }
  })
}
function handleDetailPageChange(page) {
  detailPageNum.value = page
  fetchOrderDetail()
}
function handleDetailSizeChange(size) {
  detailPageSize.value = size
  detailPageNum.value = 1
  fetchOrderDetail()
}
function resetDetailDialog() {
  orderDetailList.value = []
  detailTotal.value = 0
  detailPageNum.value = 1
  currentOrderId = null
}
function updateOrderStatus(row) {
  // 订单状态1-6，循环修改
  const currentStatus = Object.values(statusMap).indexOf(row.status) + 1
  let nextStatus = currentStatus + 1
  if (nextStatus > 6) nextStatus = 1
  axios.post('/api/order/updateOrder', {
    id: row.orderNo,
    status: nextStatus
  }).then(res => {
    if (res.data.code === 1) {
      // 如果是5->6，调用updateDishMonthSale
      if (currentStatus === 5 && nextStatus === 6) {
          axios.post(`/api/order/updateDishMonthSale?id=${row.orderNo}`)
          .then(() => {
            fetchOrders()
          })
      } else {
        fetchOrders()
      }
    }
  })
}
function resetSearch() {
  searchStatus.value = undefined
  searchOrderTime.value = undefined
  searchTableId.value = undefined
  searchAmount.value = undefined
  searchPayStatus.value = undefined
  currentPage.value = 1
  fetchOrders()
}
// 图片预览（本地路径或服务器路径都可）
const getImagePreview = (url) => {
  // 如果后端返回的是绝对路径，建议处理成可访问的静态资源URL
  // 这里假设后端返回的路径可直接访问，否则需要你自己拼接前缀
  if (url.startsWith('http')) return url
  // 例如：将 D:/upload/xxx.jpg 替换为 http://localhost:8080/upload/xxx.jpg
  // 你可以根据实际情况调整
  const filename = url.split(/[\\/]/).pop()
  return '/api/images/' + filename
}

onMounted(() => {
  fetchOrders()
})

watch(currentPage, () => {
  fetchOrders()
})
</script>

<style scoped>
.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  margin-bottom: 12px;
}
</style> 